package com.picturehistory.core.jersey.util;

import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4186838284339234065L;

	public static final String STYPE = "AES";
	public static final int KEY_LENGTH = 256; // some spec does not support

	private SecretKeySpec skeySpec;


	private Cipher getCipher() {
		Cipher ret = null;
		try {
			ret = Cipher.getInstance(STYPE);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
		return ret;
	}

	public AES() throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance(STYPE);
		kgen.init(KEY_LENGTH);
		//
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		//
		this.skeySpec = new SecretKeySpec(raw, STYPE);
	}

	public byte[] encode(String msg) {
		byte[] encrypted = null;
		Cipher c = getCipher();
		try {
			c.init(Cipher.ENCRYPT_MODE, this.skeySpec);
			encrypted = c.doFinal(msg.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encrypted;
	}

	public String decode(byte[] msg) {
		byte[] decoded = null;
		Cipher c = getCipher();
		try {
			c.init(Cipher.DECRYPT_MODE, this.skeySpec);
			decoded = c.doFinal(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String(decoded);
	}
}
